<template>
  <div class="student-layout">
    <el-container>
      <el-header>
        <div class="header-content">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="handleAvatarUpload"
          >
            <el-avatar 
              :size="40" 
              :src="avatarUrl || defaultAvatar"
              @error="handleAvatarError"
            />
          </el-upload>
          <div class="logo">考试系统</div>
          <div class="user-info">
            <el-dropdown>
              <span class="el-dropdown-link">
                学号：{{ studentId }}<el-icon class="el-icon-right"><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :icon="SwitchButton" @click="logout">安全退出</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <el-menu
            :default-active="activeMenu"
            class="el-menu-vertical"
            @select="handleSelect"
          >
            <el-menu-item index="/student/home">
              <el-icon><House /></el-icon>
              <span>首页</span>
            </el-menu-item>
            <el-menu-item index="/student/exam-management">
              <el-icon><Document /></el-icon>
              <span>考试管理</span>
            </el-menu-item>
            <el-menu-item index="/student/exam-details">
              <el-icon><List /></el-icon>
              <span>考试详情</span>
            </el-menu-item>
            <el-menu-item index="/student/ranking">
              <el-icon><Trophy /></el-icon>
              <span>排行榜</span>
            </el-menu-item>
            <el-menu-item index="/student/profile">
              <el-icon><User /></el-icon>
              <span>学生信息</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Document, List, Trophy, User, ArrowDown, SwitchButton, House } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const studentId = ref('')
const activeMenu = ref('/student/home')

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
// 当前头像URL
const avatarUrl = ref('')

// 头像上传前的验证
const beforeAvatarUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG) {
        ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    }
    if (!isLt2M) {
        ElMessage.error('头像大小不能超过 2MB!')
    }
    return isJPG && isLt2M
}

// 处理头像上传
const handleAvatarUpload = async (options: { file: File }) => {
    try {
        const file = options.file
        // 将文件转换为 base64
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
            avatarUrl.value = reader.result as string
            // 保存到 sessionStorage
            sessionStorage.setItem('userAvatar', reader.result as string)
            ElMessage.success('头像更新成功')
        }
    } catch (error) {
        console.error('头像上传失败:', error)
        ElMessage.error('头像上传失败')
    }
}

// 处理头像加载错误
const handleAvatarError = () => {
    avatarUrl.value = defaultAvatar
}

onMounted(() => {
  // 从localStorage或store中获取学生信息
  studentId.value = localStorage.getItem('studentId') || ''
  activeMenu.value = route.path

  // 加载保存的头像
  const savedAvatar = sessionStorage.getItem('userAvatar')
  if (savedAvatar) {
    avatarUrl.value = savedAvatar
  }
})

const handleSelect = (key: string) => {
  router.replace(key)
}

// 添加安全退出功能
const logout = () => {
  // 保存当前头像
  const currentAvatar = sessionStorage.getItem('userAvatar')
  // 清空本地存储
  localStorage.clear()
  // 清空 sessionStorage
  sessionStorage.clear()
  // 恢复头像
  if (currentAvatar) {
    sessionStorage.setItem('userAvatar', currentAvatar)
  }
  // 跳转到登录页面
  router.push('/login')
}
</script>

<style scoped>
.student-layout {
  height: 100vh;
}

.el-header {
  background-color: #409EFF;
  color: white;
  padding: 0 20px;
}

.header-content {
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  font-size: 20px;
  font-weight: bold;
}

.user-info {
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.avatar-uploader {
  cursor: pointer;
}

.avatar-uploader :deep(.el-upload) {
  border-radius: 50%;
  overflow: hidden;
}

.el-dropdown-link {
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.el-icon-right {
  margin-left: 5px;
}

.el-aside {
  background-color: #f5f7fa;
}

.el-menu-vertical {
  height: 100%;
  border-right: none;
}

.el-main {
  padding: 20px;
  background-color: #f0f2f5;
}
</style> 